package view;

import javax.swing.*;
import java.awt.*;
import model.Book;
import dao.BookDAO;
import javax.swing.table.DefaultTableModel;
import java.util.List;

public class BookPanel extends JPanel {
    private JTable bookTable;
    private JTextField searchField;
    private DefaultTableModel tableModel;
    
    public BookPanel() {
        setLayout(new BorderLayout());
        
        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        searchField = new JTextField(20);
        JButton searchBtn = new JButton("搜索");
        JButton addBtn = new JButton("添加图书");
        JButton editBtn = new JButton("编辑");
        JButton deleteBtn = new JButton("删除");
        JButton refreshBtn = new JButton("刷新");
        
        searchPanel.add(new JLabel("书名："));
        searchPanel.add(searchField);
        searchPanel.add(searchBtn);
        searchPanel.add(addBtn);
        searchPanel.add(editBtn);
        searchPanel.add(deleteBtn);
        searchPanel.add(refreshBtn);
        
        // 设置按钮样式
        styleButton(searchBtn);
        styleButton(addBtn);
        styleButton(editBtn);
        styleButton(deleteBtn);
        styleButton(refreshBtn);
        
        add(searchPanel, BorderLayout.NORTH);
        
        // 图书表格
        initTable();
        
        // 添加按钮事件
        searchBtn.addActionListener(e -> searchBooks());
        addBtn.addActionListener(e -> {
            AddBookDialog dialog = new AddBookDialog((JFrame) SwingUtilities.getWindowAncestor(this), this);
            dialog.setVisible(true);
        });
        editBtn.addActionListener(e -> editSelectedBook());
        deleteBtn.addActionListener(e -> deleteSelectedBook());
        refreshBtn.addActionListener(e -> refreshTable());
        
        // 添加搜索框回车事件
        searchField.addActionListener(e -> searchBooks());
        
        // 初始加载数据
        refreshTable();
    }
    
    private void styleButton(JButton button) {
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setFocusPainted(false);
        button.setBackground(new Color(59, 89, 152));
        button.setForeground(Color.WHITE);
        button.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
    }
    
    private void searchBooks() {
        String searchText = searchField.getText().trim();
        BookDAO dao = new BookDAO();
        List<Book> books = dao.searchBooks(searchText);
        updateTableData(books);
    }
    
    public void refreshTable() {
        BookDAO dao = new BookDAO();
        List<Book> books = dao.getAllBooks();
        updateTableData(books);
    }
    
    private void updateTableData(List<Book> books) {
        tableModel.setRowCount(0);
        for (Book book : books) {
            Object[] row = {
                book.getId(),
                book.getTitle(),
                book.getAuthor(),
                book.getPrice(),
                book.getStock()
            };
            tableModel.addRow(row);
        }
    }
    
    private void editSelectedBook() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow >= 0) {
            Book book = new Book(
                (int) tableModel.getValueAt(selectedRow, 0),
                (String) tableModel.getValueAt(selectedRow, 1),
                (String) tableModel.getValueAt(selectedRow, 2),
                (double) tableModel.getValueAt(selectedRow, 3),
                (int) tableModel.getValueAt(selectedRow, 4)
            );
            
            EditBookDialog dialog = new EditBookDialog(
                (JFrame) SwingUtilities.getWindowAncestor(this),
                this,
                book
            );
            dialog.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要编辑的图书！");
        }
    }
    
    private void deleteSelectedBook() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow >= 0) {
            int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要删除这本图书吗？",
                "确认删除",
                JOptionPane.YES_NO_OPTION
            );
            
            if (confirm == JOptionPane.YES_OPTION) {
                int bookId = (int) tableModel.getValueAt(selectedRow, 0);
                BookDAO dao = new BookDAO();
                if (dao.deleteBook(bookId)) {
                    JOptionPane.showMessageDialog(this, "删除成功！");
                    refreshTable();
                } else {
                    JOptionPane.showMessageDialog(this, "删除失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要删除的图书！");
        }
    }
    
    private void initTable() {
        String[] columns = {"ID", "书名", "作者", "价格", "库存"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
            
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex == 0 || columnIndex == 4) return Integer.class;
                if (columnIndex == 3) return Double.class;
                return String.class;
            }
        };
        
        bookTable = new JTable(tableModel);
        bookTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        bookTable.setRowHeight(25);
        bookTable.getTableHeader().setReorderingAllowed(false);
        
        // 设置列宽
        bookTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        bookTable.getColumnModel().getColumn(1).setPreferredWidth(200);
        bookTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        bookTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        bookTable.getColumnModel().getColumn(4).setPreferredWidth(100);
        
        // 设置表格字体
        Font font = new Font("微软雅黑", Font.PLAIN, 14);
        bookTable.setFont(font);
        bookTable.getTableHeader().setFont(font);
        
        // 设置表格行高亮
        bookTable.setSelectionBackground(new Color(184, 207, 229));
        
        JScrollPane scrollPane = new JScrollPane(bookTable);
        add(scrollPane, BorderLayout.CENTER);
    }
    
    public void requestSearchFocus() {
        searchField.requestFocusInWindow();
    }
} 